var portaluserno = getCookie('portaluserno')
var configInfo = InitialParameter("/Config.json");
var modelApi = getBaseplatformPort()
var monitoringData = []
$(document).ready(function () {
    if (!portaluserno) {
        location.href = "/"
    } else {
        getMonData()
        echartsData()
        monNameSearch()
        tableFun()
    }
})

function echartsData() {
    var myChart = echarts.init(document.getElementById('platformAccessEchartImg'), 'walden');
    // var myChart1 = echarts.init(document.getElementById('onlineUsersImg'), 'walden');

    var option = {
        tooltip: {
            formatter: "{a}{b} : {c}"
        },
        series: [{
                type: 'gauge',
                detail: {
                    formatter: '{value}'
                }, //仪表盘显示数据
                axisLine: { //仪表盘轴线样式
                    lineStyle: {
                        width: 10
                    }
                },
                splitLine: { //分割线样式
                    length: 10
                },
                data: [{
                    value: monitoringData.executingCount,
                    name: '在线应用数'
                }],
            }

        ]
    }
    // var option1 = {
    //     tooltip: {
    //         trigger: 'axis'
    //     },
    //     legend: {
    //         data: ['成功','失败']
    //     },
    //     grid: {
    //         left: '3%',
    //         right: '4%',
    //         bottom: '3%',
    //         containLabel: true
    //     },
    //     xAxis: {
    //         name: '名称',
    //         data: ['应用数量', '通用分析', '专题应用'],
    //     },
    //     yAxis: {
    //         name: '个数',
    //         type: 'value',
    //     },
    //     series: [{
    //         name: '应用数量',
    //         type: 'line',
    //         stack: 'Total',
    //         data: [120, 132, 101]
    //     }, {
    //         name: '成功',
    //         type: 'bar',
    //         data: [134, 90, 210],
    //         barWidth:'10px'
    //     }, {
    //         name: '失败',
    //         type: 'bar',
    //         data: [134, 230, 210],
    //         barWidth:'10px'
    //     }]
    // }
    myChart.setOption(option)
    // myChart1.setOption(option1)
    window.onresize = function () {
        myChart.resize();
        // myChart1.resize();
    }

}

function getMonData() {
    var results = sendAjax(modelApi + "resource/applyMonitoring", "POST");
    if (results.code == 200) {
        monitoringData = results.data
        $('#applicationNumbers').html(monitoringData.applyCount)
        $('#projectApplication').html(monitoringData.ztCount)
        $('#generalAnalysis').html(monitoringData.tyCount)
        $('#cumulativeNumber').html(monitoringData.runCount)
        $('#successfulNumber').html(monitoringData.successCount)
        $('#failedNumber').html(monitoringData.failedCount)
        let contNameHtml = ''
        let arr = ['rgb(249, 249, 249)', '#fff']
        monitoringData.hotApply.map((item, index) => {
            let color
            if (index % 2 == 0) {
                color = arr[0]
            } else {
                color = arr[1]
            }
            contNameHtml += `
                <div class="cont" style="background:${color};">
                    <div>${item.MODEL_NAME}</div>
                    <div>${item.COUNT}</div>
                </div>
            `
        })
        $('#contName').html(contNameHtml)


    } else {
        layer.msg('获取失败')
    }
}

function sendAjax(url, type, data) {
    $.ajaxSettings.async = false;
    var results;
    $.ajax({
        type: type,
        dataType: "json",
        url: url,
        data: data,
        success: function (data) {
            results = data;
        },
        error: function (error) {
            results = error;
        }
    });
    return results;
}
let selectData = []
let selectTwoData = []

function tebleDataFun() {
    let results = sendAjax(modelApi + "apply/getApplyCatalog", "POST", {
        deptId: getCookie('portaluserdept')
    });
    if (results.code == '200') {
        selectData = results.data
        for (i in results.data) {
            $('#erviceTypeFirst').append(`<option value="${i}">${i}</option>`)
        } 
        form.render('select') 
    } else {
        layer.msg('获取失败')
    }
    
}

function tableFun() {
    window.onload = function () {
        monFun()
        tebleDataFun()
    }
}

function monFun() {
    let ipt_date = $('#ipt_date').val()
    /*
        专题应用 serviceType1： ZT  NO
        通用分析 serviceType1：ZY  NO 
        其他 serviceType1： QT  ORG_ID
    */
    let servece1 = null
    let serveceid = null
    let paramsPObj = {}
    if ($('#erviceTypeFirst').val() == '专题应用') servece1 = 'ZT'
    if ($('#erviceTypeFirst').val() == '通用分析') servece1 = 'TY'
    if ($('#erviceTypeFirst').val() == '其他') servece1 = 'QT'
    if ($('#erviceTypeFirst').val() == '其他') {
        selectTwoData.map(item => {
            if (item.NAME == $('#erviceTypeTwo').val()) {
                serveceid = item.ORG_ID
            }
        })
        paramsPObj = {
            'serviceType1': servece1,
            'serviceType2': serveceid,
            'startTime':$.trim(ipt_date.substring(0,10)),
            'endTime':$.trim(ipt_date.substring(13)),
            'key':$('#applicationName').val(),
        }
    } else {
        selectTwoData.map(item => {
            if (item.NAME == $('#erviceTypeTwo').val()) {
                serveceid = item.NO
            }
        })
        paramsPObj = {
            'serviceType1': servece1,
            'serviceType2': serveceid,
            'startTime':$.trim(ipt_date.substring(0,10)),
            'endTime':$.trim(ipt_date.substring(13)),
            'key':$('#applicationName').val(),
        }
    }
    let tableResults = sendAjax(modelApi + "resource/applyMonitoringTables ", "POST", paramsPObj);

    tableResults.data.map(item => {
        Object.assign(item, { 
            endtime: item.END_TIME == '' ? '无' : getYMDHMS (item.END_TIME),
            starttime: item.INSERT_TIME == '' ? '无' : getYMDHMS (item.INSERT_TIME) ,
            a: '坡度分析',
        })
    }) 
    tableResults.data.sort(creatCompare ('INSERT_TIME'))

    
    table.render({
        elem: '#serviceMonitoringTable',
        page: true //开启分页
            ,
        data: tableResults.data,
        cols: [
            [ //表头
                {
                    type: 'numbers',
                    title: '序号',
                    sort: true,
                    align: 'center',
                    width: 100
                }, {
                    field: 'MODEL_NAME',
                    title: '应用名称',
                    align: 'center'
                }, {
                    field: 'sex',
                    title: '应用类型（一级）',
                    align: 'center',
                    templet: function (d) {
                        let text = ''
                        if (d.TYPE == "1") {
                            text = '专题分析'
                        } else if (d.TYPE == "2") {
                            text = '通用分析'
                        }
                        //得到当前行数据，并拼接成自定义模板
                        return text
                    }
                }, {
                    field: 'a',
                    title: '应用类型（二级）',
                    align: 'center'
                }, {
                    field: 'JOB_STATUS',
                    title: '服务状态',
                    align: 'center'
                }, {
                    field: 'starttime',
                    title: '执行起始时间',
                    align: 'center'
                }, {
                    field: 'endtime',
                    title: '执行结束时间',
                    align: 'center'
                }, {
                    field: 'USERNAME',
                    title: '执行人',
                    align: 'center'
                }
                // ,{field: 'wealth', title: '查看日志',align:'center'}
            ]
        ]
    });
}
// 时间排序 
function creatCompare(propertyName) {
    return function (obj1, obj2) {
        var value1 = obj1[propertyName];
        var value2 = obj2[propertyName];
        if (value1 > value2) {
            return -1
        } else if (value1 < value2) {
            return 1
        } else {
            return 0
        }
    }
}

function getYMDHMS (timestamp) {
    let time = new Date(timestamp)
    let year = time.getFullYear()
    const month = (time.getMonth() + 1).toString().padStart(2, '0')
    const date = (time.getDate()).toString().padStart(2, '0')
    const hours = (time.getHours()).toString().padStart(2, '0')
    const minute = (time.getMinutes()).toString().padStart(2, '0')
    const second = (time.getSeconds()).toString().padStart(2, '0')

    return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
}

function monNameSearch() {
    $('#btn_search').on('click', function () {
        monFun () 
    })
}
// http://localhost:8889/sw/resource/applyMonitoringTables 
/*
    type 1 专题分析
        2 通用分析 

*/
/*
服务类型（一级）：
    sw/apply/getApplyCatalog  deptId: 101010 当前部门id
    /sw/apply/getApplys menuName: 其它分析服务
                        userId: admin

*/